package com.device.annotation.support;

import com.alibaba.fastjson.JSONObject;
import com.device.annotation.LoginUser;
import com.device.util.JWTUtil;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
    public static final String LOGIN_TOKEN_KEY = "Authorization";

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(Integer.class)
                && parameter.hasParameterAnnotation(LoginUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container, NativeWebRequest request,
                                  WebDataBinderFactory factory) {

        String token = request.getHeader(LOGIN_TOKEN_KEY);
        if (token != null) {
            token = token.replace("Token ", "");
        }
        Object obj = JWTUtil.parseJWT(token);
        JSONObject jsonObject = JSONObject.parseObject(obj.toString());
        return jsonObject.getInteger("id");
    }
}

